<?php 
namespace Common\Util;
/**
 * 任务工具
 * @author liuyang
 * @version 2.0
 * @since 20160417
 */
class TaskUtils {
    
    const EVERY_TASK_TIME=120;
    const ROLE_MASTER="master";
    
    /**
     * 主备切换逻辑
     */
    private static function _masterControl($cacheName,$lockExpireTime=120){
        CacheUtils::lock($cacheName."_lock",$lockExpireTime);
        // echo self::getIp();
        //根据CLI传的参数，判定谁是主执行线程
        $rolelist = getopt("r:");
        $role = $rolelist['r'];
        $curCacheTime = CacheUtils::get($cacheName); 
        $nowTime = time();
        //echo date("Y-m-d H:i:s",$curCacheTime).PHP_EOL;
        //echo $nowTime-$curCacheTime;
        // exit();
        //如果小于2分钟都不执行
        if(($nowTime-$curCacheTime) <= self::EVERY_TASK_TIME){
            exit("有线程正在执行中....".PHP_EOL);
        }
         
        //如果是主纯程，直接执行
        if($role == self::ROLE_MASTER){
            //保存30天
            CacheUtils::set($cacheName, $nowTime,30*24*3600);
        }else{
            //如果当前时间减去缓存中的时间大于10分钟就执行slave线程
            if(($nowTime-$curCacheTime) < 600){
                exit("等待".(600-$nowTime+$curCacheTime)."s，主线程确认不执行了....".PHP_EOL);
            }
            //保存十分钟
            CacheUtils::set($cacheName, $nowTime,30*24*3600);
        }
        return $role;
    
    }
	  
    
    public static function single($cacheName,$lockExpireTime=120){
        self::_masterControl($cacheName,$lockExpireTime); 
    }
    
    public static function multi($class,$method,$cacheName,$lockExpireTime=120){
        $role = self::_masterControl($cacheName,$lockExpireTime); 
        $role="";
        set_time_limit(0);
         
        $count = 0;
        $isContinue = true;
        $loadTime = time();
        while($isContinue){
            $count ++;
            $whileTime = time();
            //每2分钟退出系统或者执行25000条，防止超出内存
            if($whileTime-$loadTime>=self::EVERY_TASK_TIME || $count>20000){
                CacheUtils::set($cacheName, null);
                exit("running ".$count." records finished");
            } 
            $isEmpty=call_user_func(array($class, $method)); 
            echo $role."线程正在[".date("Y-m-d H:i:s",$whileTime)."]执行中....".PHP_EOL;
            if($isEmpty){
                sleep(1);
            }
            @ob_flush();
        }
    }
 
	 
}
?>